package com.school.gmz.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.school.gmz.common.Result;
import com.school.gmz.entity.BookLend;
import com.school.gmz.mapper.BookLendMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@RestController
@RequestMapping("/booklend")
@Api(tags = "书籍借阅管理") // 定义API的分类
public class BookLendController {
    @Resource
    BookLendMapper booklendMapper;

    // 添加用户的书籍借阅记录
    @PostMapping
    @ApiOperation(value = "添加书籍借阅记录", notes = "添加书籍借阅记录的详细信息")
    public Result<?> save(@RequestBody BookLend booklend){
        booklendMapper.insert(booklend);
        return Result.success();
    }

    // 更新书籍借阅记录
    @PutMapping
    @ApiOperation(value = "更新书籍借阅记录", notes = "根据ID更新书籍借阅记录的详细信息")
    public Result<?> update(@RequestBody BookLend booklend){
        booklendMapper.updateById(booklend);
        return Result.success();
    }

    // 删除书籍借阅记录
    @DeleteMapping("/{id}")
    @ApiOperation(value = "删除书籍借阅记录", notes = "根据ID删除书籍借阅记录")
    public Result<?> delete(@ApiParam(value = "书籍借阅记录ID", required = true) @PathVariable Long id){
        booklendMapper.deleteById(id);
        return Result.success();
    }

    // 查询书籍借阅记录
    @GetMapping
    @ApiOperation(value = "查询书籍借阅记录", notes = "支持分页和关键字搜索")
    public Result<?> findPage(@ApiParam(value = "页码", defaultValue = "1") @RequestParam(defaultValue = "1") Integer pageNum,
                              @ApiParam(value = "每页记录数", defaultValue = "10") @RequestParam(defaultValue = "10") Integer pageSize,
                              @ApiParam(value = "搜索关键字", defaultValue = "") @RequestParam(defaultValue = "") String search,
                              @ApiParam(value = "作者名字", defaultValue = "") @RequestParam(defaultValue = "") String author,
                              @ApiParam(value = "位置", defaultValue = "") @RequestParam(defaultValue = "") String position){
        LambdaQueryWrapper<BookLend> wrapper = Wrappers.<BookLend>lambdaQuery();
        if (StrUtil.isNotBlank(search)){
            wrapper.like(BookLend::getName,search);
        }
        if (StringUtils.isNotBlank(author)) {
            wrapper.like(BookLend::getAuthor, author);
        }
        if (StringUtils.isNotBlank(position)) {
            wrapper.like(BookLend::getPosition, position);
        }
        Page<BookLend> BookLendPage = booklendMapper.selectPage(new Page<>(pageNum, pageSize), wrapper);
        return Result.success(BookLendPage);
    }
}